package com.springboot.demo.design.pattern.processor;

import com.springboot.demo.design.pattern.processor.impl.UserProcessor;
import com.springboot.demo.design.pattern.processor.impl.UserProcessorImpl;
import java.lang.reflect.Proxy;
import java.util.concurrent.locks.ReentrantLock;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * 处理器代理工厂,可以动态代理获取各种处理器
 *
 * @author supu
 * @date 2019-03-19 16:43
 **/
@Log4j2
@Component
public class ProcessorProxyFactory {
    private UserProcessor userProcessor;
    @Autowired
    private PlatformTransactionManager transactionManager;

    private ReentrantLock reentrantLock = new ReentrantLock();

    public UserProcessor getUserProcessor() {
        if (userProcessor != null) {
            return userProcessor;
        }

        try {
            reentrantLock.lock();
            if (userProcessor == null) {
                userProcessor = (UserProcessor) getProcessor(new UserProcessorImpl());
            }
        } catch (Exception e) {
            log.error("userProcessor get proxy object error:{}", e);
        } finally {
            reentrantLock.unlock();
        }
        return userProcessor;
    }

    private Processor getProcessor(Object target) {
        return (Processor) Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), new CustomInvocationHandler(target, transactionManager));
    }

    /*private UserProcessor getProcessor(Class clz, Object target) {
        UserProcessor userProcessor = new UserProcessorImpl();

        UserProcessor userProcessor1 = (UserProcessor)Proxy.newProxyInstance(userProcessor.getClass().getClassLoader(),userProcessor.getClass().getInterfaces(),new CustomInvocationHandler(userProcessor));
        log.warn("processor:{}", userProcessor1);
        return userProcessor1;
    }*/
}
